package BFS.多源最短路问题;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Date 2024/9/10 22:07
 * @description: 正难则反: 飞地的数量
 * .
 * @Author LittleNight
 */
public class likou1020 {


    // bfs 用标记数组和sz
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    int m, n;
    boolean[][] vis;
    public int numEnclaves(int[][] grid) {
        m = grid.length; n = grid[0].length;
        vis = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        // 1. 先添加所有的1 . 边界上的1
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(i == 0 || i == m - 1 || j == 0 || j == n - 1) {
                    if(grid[i][j] == 1) {
                        vis[i][j] = true;
                        // 多源bfs, 加入所有的 1
                        queue.offer(new int[]{i, j});
                    }
                }
            }
        }
        // 2. bfs 主逻辑
        // int step = 0;
        while(!queue.isEmpty()) {
            int sz = queue.size();
            // 弹出下一层
            while(sz-- != 0) {
                int[] tmp = queue.poll();
                int a = tmp[0], b = tmp[1];
                for (int i = 0; i < 4; i++) {
                    int x = a + dx[i], y = b + dy[i];
                    if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && grid[x][y] == 1) {
                        vis[x][y] = true; // 标记这个位置添加过
                        queue.offer(new int[]{x, y}); // 添加到队列
                    }
                }
            }
        }
        // 3. 遍历原数组, 提取结果
        int ret = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j] == 1 && !vis[i][j]) ret++;
            }
        }
        return ret;
    }

}
